<script setup>
import { ref, watch } from 'vue'
import { onSearchApi } from '@/apis/search.js'
import ListCard from '@/components/ListCard/ListCard.vue'
import { useAudioStore } from '@/stores/audioStore'
import { ElMessage } from 'element-plus'
import bus from '@/utils/bus'

const useAudio = useAudioStore()

const props = defineProps({
  searchName: {
    type: String
  }
})

// 搜索结果
const searchList = ref([])

// 触底加载
const isSongLoad = ref(false)
const loadSearchSongsList = async () => {
  bus.emit('changeIsLoading', true)
  const { data } = await onSearchApi(props.searchName, 1, 30, searchList.value.length)
  searchList.value.push(...data.result.songs)
  bus.emit('changeIsLoading', false)
  if (!data.result.songs.length) {
    isSongLoad.value = true
    return ElMessage('到底啦')
  }
}

// props.searchName 变化时，触发搜索
watch(() => props.searchName, async () => {
  const { data } = await onSearchApi(props.searchName, 1, 30, searchList.value.length)
  searchList.value = data.result.songs
})
</script>

<template>
  <div v-infinite-scroll="loadSearchSongsList" :infinite-scroll-delay="500" :infinite-scroll-disabled="isSongLoad">
    <ListCard v-for="(song, index) in searchList" :key="song.id" :song="song" :index="index" @play="useAudio.activeSongList = searchList" />
  </div>
  <div class="bottom" v-if="isSongLoad">
    —————————— 到底线了 ——————————
  </div>
</template>

<style scoped lang='scss'>
.bottom {
  line-height: 80px;
  text-align: center;
  color: #aaa;
}
</style>
